﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Sitecore.Data.Items;
using System.Web.UI.HtmlControls;

namespace Workflow.Alerts.Sublayouts
{
    public partial class NewAlertPage : BaseControl, INewAlertView
    {
        #region INewAlertView Members

        public Int32? Id
        {
            get
            {
                int id;
                if (Request.QueryString["alertId"] != null &&
                    Int32.TryParse(Request.QueryString["alertId"], out id))
                {
                    return id;
                }
                return null;
            }
        }

        public Boolean IsMarker
        {
            get
            {
                return rdMarker.Checked;
            }
            set
            {
                if (value)
                    rdMarker.Checked = true;
                else
                    rdArea.Checked = true;
            }
        }

        public DataTable MunicipalityList
        {
            set
            {
                rptMunicipality.DataSource = value;
                rptMunicipality.DataBind();
            }
        }

        public Int32? Municipality
        {
            get
            {
                if (!String.IsNullOrEmpty(selectedMunicipality.Value))
                    return Int32.Parse(selectedMunicipality.Value);
                return null;
            }
            set
            {
                foreach (RepeaterItem item in rptMunicipality.Items)
                {
                    var municiaplityid = (HtmlInputHidden)item.FindControlRecursive("municipalityid");
                    if (municiaplityid != null && municiaplityid.Value == value.Value.ToString())
                    {
                        RadioButton radioButton = (RadioButton)item.FindControl("rbMunicipality");
                        if (radioButton != null)
                            radioButton.Checked = true;
                    }
                }
                selectedMunicipality.Value = value.ToString();
            } //select checkbox in repeater 
        }

        public String CenterCoordinates
        {
            get { return coordinatesMarker.Value; }
            set { coordinatesMarker.Value = value; }
        }

        public String AreaCoordinates
        {
            get { return coordinatesArea.Value; }
            set { coordinatesArea.Value = value; }
        }

        public IDictionary<int, string> AlertTypeList
        {
            set
            {
                ddlAlertType.DataSource = value;
                ddlAlertType.DataValueField = "key";
                ddlAlertType.DataTextField = "value";
                ddlAlertType.DataBind();
            }
        }

        public Int32 AlertType
        {
            get
            {

                return Int32.Parse(ddlAlertType.SelectedItem.Value);
            }
            set
            {
                ddlAlertType.Items.FindByValue(value.ToString()).Selected = true;
            }
        }

        public IDictionary<int, string> ActivityTypeList
        {
            set
            {
                ddlActivity.DataSource = value;
                ddlActivity.DataValueField = "key";
                ddlActivity.DataTextField = "value";
                ddlActivity.DataBind();
            }
        }

        public Int32 ActivityType
        {
            get
            {
                return Int32.Parse(ddlActivity.SelectedItem.Value);
            }
            set
            {
                ddlActivity.Items.FindByValue(value.ToString()).Selected = true;
            }
        }

        public DataTable PersonList
        {
            set
            {
                ddlPerson.DataSource = value;
                ddlPerson.DataTextField = "name";
                ddlPerson.DataValueField = "id";
                ddlPerson.DataBind();
            }
        }

        public Int32 Person
        {
            get
            {
                return Int32.Parse(ddlPerson.SelectedItem.Value);
            }
            set
            {
                //ddlPerson.Items.FindItemByValue(value.ToString()).Selected = true;
                ddlPerson.Items.FindByValue(value.ToString()).Selected = true;
            }
        }

        public Int32 AlertArea
        {
            get { return Int32.Parse(txtArea.Text); }
            set { txtArea.Text = value.ToString(); }
        }

        public DateTime EstimateStartDate
        {
            get
            {
                return rdpEstimateStartDate.SelectedDate.Value;

            }
            set
            {
                rdpEstimateStartDate.SelectedDate = value;
            }
        }

        public DateTime EstimateEndDate
        {
            get
            {
                return rdpEstimateEndDate.SelectedDate.Value;

            }
            set
            {
                rdpEstimateEndDate.SelectedDate = value;
            }
        }

        public String TrafficComments
        {
            get { return txtTrafficComments.Text; }
            set { txtTrafficComments.Text = value; }
        }

        public DataTable Locations
        {
            set
            {
                //rcbLocation.DataSource = value;
                //rcbLocation.DataTextField = "name";
                //rcbLocation.DataBind();
            }
        }

        public String Location
        {
            get
            {
                return rcbLocation.Text;
            }
            set
            {
                rcbLocation.Text = value;
            }
        }

        public String LocationDescription
        {
            get { return txtLocationDescription.Text; }
            set { txtLocationDescription.Text = value; }
        }

        public Boolean HasTrafficProblems
        {
            get { return Boolean.Parse(rblTrafficProblems.SelectedItem.Value); }
            set
            {
                rblTrafficProblems.ClearSelection();
                rblTrafficProblems.Items.FindByValue(value.ToString()).Selected = true;
            }
        }

        public event OnNewAlertViewLoad OnNewAlertLoad;
        public event OnNewAlertViewSave OnNewAlertSave;
        public event OnNewAlertDelete DeleteAlert;

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            PresentationManager.RegisterView(typeof(NewAlertViewPresenter), this, new WebSessionProvider());
            if (!IsPostBack && OnNewAlertLoad != null)
            {
                OnNewAlertLoad();
            }
            btnDelete.Visible = Id.HasValue;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid && OnNewAlertSave != null)
            {
                OnNewAlertSave(WorkflowEnums.Status.Created);
                Item detailPageItem = (Id.HasValue) ?
                                    Sitecore.Context.Item.Parent :
                                    Sitecore.Context.Item.Axes.SelectSingleItem("../Queued");

                Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(detailPageItem));
            }
        }

        protected void btnSaveSend_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid && OnNewAlertSave != null)
            {
                Item detailPageItem;
                if (ActivityType == 8)
                {
                    OnNewAlertSave(WorkflowEnums.Status.Approved);
                    detailPageItem = (Id.HasValue) ?
                                        Sitecore.Context.Item.Axes.SelectSingleItem("../../InProgress") :
                                        Sitecore.Context.Item.Axes.SelectSingleItem("../InProgress");

                }
                else
                {
                    OnNewAlertSave(WorkflowEnums.Status.Sent);
                    detailPageItem = (Id.HasValue) ?
                                        Sitecore.Context.Item.Axes.SelectSingleItem("../../Sent") :
                                        Sitecore.Context.Item.Axes.SelectSingleItem("../Sent");
                }

                Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(detailPageItem));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            if (Id.HasValue)
            {
                var detailPageItem = Sitecore.Context.Item.Parent;
                Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(detailPageItem));                
            }
            else
            {
                if (OnNewAlertLoad != null)
                {
                    OnNewAlertLoad();
                }
            }
        }

        protected void cvLocation_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (rdMarker.Checked)
            {
                args.IsValid = !String.IsNullOrEmpty(rcbLocation.Text);
            }
            else if (rdArea.Checked)
            {
                args.IsValid = !String.IsNullOrEmpty(txtLocationDescription.Text);
            }
            else
            {
                args.IsValid = false;
            }
        }

        protected void cvArea_ServerValidate(object source, ServerValidateEventArgs args)
        {

            if (rdArea.Checked)
            {
                args.IsValid = !String.IsNullOrEmpty(coordinatesArea.Value);
            }
            else
            {
                args.IsValid = true;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Id.HasValue && DeleteAlert != null)
            {
                DeleteAlert();
                Item detailPageItem = Sitecore.Context.Item.Parent;
                Response.Redirect(Sitecore.Links.LinkManager.GetItemUrl(detailPageItem));
            }
        }

        protected void rptMunicipality_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    if (e.Item.DataItem != null && e.Item.DataItem is DataRowView)
                    {
                        RadioButton radioButton = (RadioButton)e.Item.FindControl("rbMunicipality");
                        string script = string.Format("SetButton({0},this,'{1}')", ((DataRowView)e.Item.DataItem)["id"], "rptMunicipality.*Municipality");
                        radioButton.Attributes.Add("onclick", script);
                    }
                }
            }

            catch (Exception exception)
            {

                //handle your exception 
            }
        }

        #endregion
    }
}